<template>
  <div class="product_file_list">
    <div class="upload_con" v-if="isEdit">
      <uploadFile ref="uploadFileRef" v-bind="uploadProps" :refnameBase="refname" @changeFile="changeFile" v-model="uploadFileData"></uploadFile>
    </div>

    <div class="upload_moudle_cont">
      <div class="file_list_document">
        <div class="line_flex">
          <div class="firstTd">
            <span v-if="!draggingBool">{{$t("goods_batchUploads_productMainImage.picture_no")}}</span>
            <span v-else>{{$t("goods_batchUploads_productMainImage.picture_no_drag")}}</span>
          </div>
          <div class="secondTd" v-if="type == 'main'">{{$t("goods_batchUploads_productMainImage.default_image")}}</div>
          <div class="picTd">{{$t("goods_batchUploads_productMainImage.image_thumbnail")}}</div>
          <div>{{$t("goods_archive.picture_name")}}</div>
          <div class="oprationTd" v-if="isEdit">{{$t("merak.action")}}</div>
        </div>

        <el-scrollbar :height="`calc(100vh - ${maxHei}px)`">
          <draggable
            ref="dragRef"
            v-model="dragArr"
            class="drag_line"
            :disabled="!draggingBool"
            group="image"
            @start="dragging = true"
            @end="dragging = false"
            @change="dragChange"
            ghost-class="ghost"
            chosen-class="chosen"
            item-key="sort"
          >
            <template #item="{ element }">
              <div class="line_flex drag_line" :class="{ line_flex_drag: draggingBool }">
                <div class="firstTd">{{ element.sort }}</div>
                <div class="secondTd" v-if="type == 'main'">
                  <span class="setMainDefault" v-show="element.is_default == 1 && !isEdit">{{$t("goods_batchUploads_productMainImage.default_image")}}</span>

                  <span v-show="isEdit"
                    ><el-switch v-model="element.currentDefault" @change="val => setDefaultFun(val, element)"
                  /></span>
                </div>
                <div class="picTd">
                  <div class="thumbnail_cont">
                    <img class="thumbnail_img" :src="element?.file_url" />
                    <div class="opration_shadow">
                      <span class="opration_icon" @click="prevewImg(sort)">
                        <el-icon><ZoomIn /></el-icon
                      ></span>
                    </div>
                  </div>
                </div>
                <div>{{ element?.name }}</div>
                <div class="oprationTd oprationTd_td" v-if="isEdit">
                  <span class="del_txt" @click="delLineFun(element)">{{$t("merak.delete")}}</span>
                </div>
              </div>
            </template>
          </draggable>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import uploadFile from "@/components/uploadFileMerak/index.vue";
import draggable from "vuedraggable";
import { ref, reactive, computed, watch } from "vue";
import { api as viewerApi } from "v-viewer";
import { DEFAULT_IMAGE } from "@/config";
import defaultImg from "@/assets/images/goods_img.webp";
const props = withDefaults(
  defineProps<{
     refname?:object;//上一个页面的refName，搭配loading使用
    tipMsg?: string;
    accept?: string; //".jpg,.jpeg,.png,.gif,.bmp,.webp", //只允许图片上传
    type?: string; //页面类型 main主图
    isEdit?: boolean; //是否可编辑
    params?: object; //其余参数
    path: string;
    draggingBool?: boolean; //拖拽
    setMainImg?: boolean; //是否开启默认
    occupyHei?: number; //内容高度
    imageType?:string;//图片类型
    imageProps?:object;//图片限制
    failBoolShow?:boolean;
  }>(),
  {
    draggingBool: false,
    path: "",
    occupyHei: 0,
    isEdit: true
  }
);

// occupyHei

const maxHei = computed(() => {
  let uploadHei = 230;
  let otherHei = 220;
  let alHei = otherHei + props.occupyHei;
  if (props.isEdit) {
    alHei = uploadHei + otherHei + props.occupyHei;
  }

  console.log(alHei, "所有高度");
  return alHei;
});

const dragRef = ref(null);
const mainDefault = ref(false); //主图设为主图
const dragging = ref(false);
const uploadProps = reactive({
  uploadLoading: true, //外部上传loading
  listType: "picture-card",
  uploadClass: "drag_upload_picture",
  path: props.path,
  fileListShow: false,
  tipMsgOther: props.tipMsg,
  accept: props.accept,
  tipShow: false,
  imageType:props.imageType,
  imageProps:props.imageProps,
  params: props.params,
  failBoolShow:props.failBoolShow
  //   maxSize:1,
});

watch(
  () => props.params,
  (newValue, oldValue) => {
    uploadProps.params = newValue;
  }
);

const uploadFileRef = ref(null);

const defaultFileArr = defineModel<Array<Record<string, any>>>({ default: [] });
console.log(defaultFileArr);
// const defaultFileArrNew = ref(JSON.parse(JSON.stringify(defaultFileArr.value)));

//查看
const prevewImg = index => {
  console.log(defaultFileArrNew.value);

  viewerApi({
    images: defaultFileArrNew.value,
    options: {
      toolbar: true,
      url: "file_url",
      fullscreen: false,
      initialViewIndex: index //默认打开哪个
    }
  });
};

/**
 * 触发dragChange事件，将当前的可拖拽列表发送给父组件。
 */
// 定义可发出的事件类型

const dragScroll = scrollTop => {
  document.querySelector(".drag_line").scrollTop = scrollTop;
};

const dragChange = event => {
  let newdragArr = JSON.parse(JSON.stringify(defaultFileArrNew.value));
  emit("dragChange", { dragArr: newdragArr, moveObj: event });
};

const uploadFileData = ref([]); //默认参数
const repateUploadFileData = ref([]); //文件夹展示
const successFileData = ref([]);
const errFileData = ref([]);

//集合所有成功的图片
const defaultFileArrNew = computed(() => {
  let fileObj = {};
  let newFileObj = [];

  repateUploadFileData.value.map((v, vindex) => {
    if (v.percentage == 100 && v.status == "success") {
      v.response.currentDefault = false;
      v.response.is_default = 0;
      fileObj[v.response.id] = v.response;
    }
  });
  newFileObj = Object.values(fileObj);

  let dragNewArr = [...defaultFileArr.value, ...newFileObj];
 
  return dragNewArr.map((dItem, dIndex) => {
    return {
      ...dItem,
      sort: dIndex + 1
    };
  });
}); 
const dragArr = ref([]);
watch(
  () => defaultFileArrNew.value,
  newValue => { 
    dragArr.value = newValue;
  },{deep:true,immediate:true}
);

 
const getSuccessUploadData = () => {
  return defaultFileArrNew.value;
};
const changeFile = fileList => {
  console.log(fileList, "change变化");
  // uploadFileRef.getJudgeFileType

  let otherFile = [];
  if (fileList.length) {
    fileList.map(fItem => {
      let type = uploadFileRef.value.getJudgeFileType(fItem);
      if (type == "zip" || type == "file") {
        //压缩包处理
        console.log(fItem);
        let successData = fItem.response?.success,
          failData = fItem.response?.fail;
        if (successData && successData.length) {
          successData.map(sItem => {
            otherFile.push({
              percentage: 100,
              status: "success",
              response: sItem
            });
          });
        }

        if (failData && failData.length) {
          failData.map(errItem => {
            otherFile.push({
              url: defaultImg,
              status: "fail",
              name: errItem.name,
              raw: {
                name: errItem.name,
                tip: errItem.msg
              }
            });
          });
        }
      } else {
        otherFile.push(fItem);
      }
    });
  }

  let uObj = {};
  uploadFileData.value.map((uItem, rIndex) => {
    if (uItem.response) {
      uObj[uItem.response.id] = uItem;
    } else {
      uObj[rIndex + 1] = uItem;
    }
  });
  uploadFileData.value = Object.values(uObj);
  // console.log(otherFile,"压缩包文件")
  // uploadFileData.value = fileList;
  repateUploadFileData.value = otherFile;
};

const getErrUploadData = () => {
  let errDataArr = [];
  repateUploadFileData.value.map((v, vindex) => {
    if (v.status == "uploading" || v.status == "ready" || v.status == "fail") {
      errDataArr.push({ ...v });
    }
  });
  return errDataArr;
};

//删除一行
const delLineFun = rows => {
  let successArr = getSuccessUploadData();

  emit("delLine", { successArr, rows });
};
//删除change数据
const delChangeFile = rows => {
  console.log(rows);
  console.log(uploadFileData.value);

  let indexFilter = uploadFileData.value.findIndex(fitem => fitem.response?.id == rows.id);

  if (indexFilter > -1) {
    uploadFileData.value.splice(indexFilter, 1);
  }

  let rObj = {};
  repateUploadFileData.value.map((rItem, rIndex) => {
    if (rItem.response) {
      rObj[rItem.response.id] = rItem;
    } else {
      rObj[rIndex + 1] = rItem;
    }
  });
  repateUploadFileData.value = Object.values(rObj);
  let repeatedIndx = repateUploadFileData.value.findIndex(ritem => ritem.response?.id == rows.id);
  console.log(repeatedIndx);
  if (repeatedIndx > -1) {
    repateUploadFileData.value.splice(repeatedIndx, 1);
    console.log(repateUploadFileData.value);
  }
};

///重新排序
const resetArr = () => {
  dragArr.value = dragArr.value.map((dItem, dIndex) => {
    return {
      ...dItem,
      sort: dIndex + 1
    };
  });
};

//设置默认值
const setDefaultFun = (val, item) => {
  item.is_default = val ? 1 : 0;
  emit("setDefault", item);
};

const emit = defineEmits<{
  delLine: any; //删除
  dragChange: any; //拖拽方法
  setDefault: any; //设置组图
}>();

defineExpose({
   baseUploadRef:computed(()=>uploadFileRef.value?.refName),
  resetArr, //重新排序
  dragScroll,
  delChangeFile, //清空change数据
  getErrUploadData
});
</script>
<style lang="scss" scoped>
@import url("./index.scss");
</style>
